package com.lee9213.mybatis.utility;

import org.mybatis.generator.api.FullyQualifiedTable;
import org.mybatis.generator.config.JDBCConnectionConfiguration;
import org.mybatis.generator.internal.JDBCConnectionFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库操作
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/30 10:59
 */
public final class DBUtil {

    private static Connection connection = null;

    public static Connection getConnection(JDBCConnectionConfiguration config) throws SQLException {
        if (connection == null) {
            JDBCConnectionFactory connectionFactory = new JDBCConnectionFactory(config);
            connection = connectionFactory.getConnection();
        }
        return connection;
    }

    /**
     * 关闭连接
     */
    public static void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }

    public static String getRemarks(JDBCConnectionConfiguration config, FullyQualifiedTable table) {
        String remarks = "";
        ResultSet rs = null;
        try {
            rs = getConnection(config).getMetaData().getTables(table.getIntrospectedCatalog(),
                    table.getIntrospectedSchema(), table.getIntrospectedTableName(), null);
            if (null != rs && rs.next()) {
                remarks = rs.getString("REMARKS");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (null != rs) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            closeConnection();
        }
        return remarks;
    }
}
